package com.service.impl;

import com.mapper.FlowMapper;
import com.mapper.GroupOrderMapper;
import com.pojo.Flow;
import com.pojo.GroupList;
import com.pojo.GroupOrder;
import com.pojo.GroupOrderExample;
import com.service.GroupListService;
import com.service.GroupOrderService;
import com.util.ServerResponse;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2020/4/8 0008.
 */
@Service
public class GroupOrderServiceImpl implements GroupOrderService {
    @Autowired
    private GroupOrderMapper groupOrderMapper;
    @Autowired
    private GroupListService groupListService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private FlowMapper flowMapper;
    @Autowired
    private Sid sid;
    @Override
    public ServerResponse save(GroupOrder groupOrder) {
        Byte status =1;
        groupOrder.setStatus(status);
        //执行mybatis添加方法
        int rows = groupOrderMapper.insert(groupOrder);
        //判断添加成功
        if (rows > 0)
            return ServerResponse.addSuccess();
        else
            return ServerResponse.addFailed();
    }

    @Override
    public ServerResponse modifyStatus(Integer id) {
        GroupOrder groupOrder = groupOrderMapper.selectByPrimaryKey(id);
        Byte status = 0;
        groupOrder.setStatus(status);
        int i = groupOrderMapper.updateByPrimaryKeySelective(groupOrder);
        if (i>0)
            return ServerResponse.deleteSuccess();
        return ServerResponse.deleteFailed();
    }

    @Override
    public ServerResponse modify(GroupOrder groupOrder) {
        int i = groupOrderMapper.updateByPrimaryKeySelective(groupOrder);
        if (i>0)
            return ServerResponse.updateSuccess();
        return ServerResponse.updateFailed();
    }

    @Override
    public ServerResponse getById(Integer id) {
        GroupOrder user = groupOrderMapper.selectByPrimaryKey(id);
        return ServerResponse.getDataSuccess(user);
    }

    @Override
    public ServerResponse getAll() {
        GroupOrderExample example=new GroupOrderExample();
        example.or(example.createCriteria().andStatusEqualTo(Byte.valueOf("1")));
        example.or(example.createCriteria().andStatusEqualTo(Byte.valueOf("2")));
        example.or(example.createCriteria().andStatusEqualTo(Byte.valueOf("3")));
        example.or(example.createCriteria().andStatusEqualTo(Byte.valueOf("4")));
        List<GroupOrder> groupOrders= groupOrderMapper.selectByExample(example);
        if (groupOrders!=null&&groupOrders.size()>0)
            return ServerResponse.getDataSuccess(groupOrders);
        return ServerResponse.getDataFailed("没有数据");
    }
    @Override
    public ServerResponse submitOrder(GroupOrder groupOrder) {
        //查询团购商品信息
        ServerResponse groupInfsr = groupListService.getById(groupOrder.getGroupId());
        //判断团购商品是否下架
        if (groupInfsr.getStatus()!=1){
            return ServerResponse.getDataFailed("商品已经下架");
        }
        //查询团购商品信息
        GroupList groupInf =(GroupList)groupInfsr.getData();
        //查询团购商品剩余数量
        int remaining  = groupInf.getGroupAll() - groupInf.getGroupCount();
        System.out.println("商品总量"+remaining);
        System.out.println("已售数量"+groupInf.getGroupCount());
        //判断团购商品是否售完
        if (remaining<=0){
            return ServerResponse.getDataFailed("商品已售完");
        }
        //设置订单状态 2为待支付
        Byte status =2;
        groupOrder.setStatus(status);
        Calendar nowTime = Calendar.getInstance();
        //设置订单下单时间
        Date orderTime = nowTime.getTime();
        //设置订单超时时间
        nowTime.add(Calendar.MINUTE,15);
        Date overTime = nowTime.getTime();
        //设置已售数量加一
        groupInf.setGroupCount(groupInf.getGroupCount()+1);
        groupListService.modify(groupInf);
        //生成订单号
        SimpleDateFormat sdf=new SimpleDateFormat("MMddHHmmss");
        String result = sdf.format(orderTime);
//        Random random=new Random();
//        for(int i=0;i<3;i++){
//            result+=random.nextInt(10);
//        }
        result+=groupOrder.getUserId();
        Long orderNum = Long.valueOf(result);
        System.out.println("生成订单号"+result);
        System.out.println("订单号"+orderNum);
        //设置团购订单信息
        groupOrder.setUnitPrice(groupInf.getGroupPrice());
        if(null==groupOrder.getProdCount()){
            groupOrder.setProdCount(1);
        }
        System.out.println("购买数量"+groupOrder.getProdCount());
        System.out.println("单价"+groupOrder.getUnitPrice());
        groupOrder.setAllPrice(groupOrder.getProdCount()*groupOrder.getUnitPrice());
        System.out.println("总价"+groupOrder.getAllPrice());
        groupOrder.setOrderNum(orderNum);
        groupOrder.setOrderTime(orderTime);
        groupOrder.setOverTime(overTime);
        //执行groupOrderMapper添加方法
        int rows = groupOrderMapper.insert(groupOrder);
        //判断添加成功
        if (rows > 0)
            return ServerResponse.addDataSuccess(groupOrder);
        else
            return ServerResponse.addFailed();
    }

    @Override
    public ServerResponse getByOrderNum(Long orderNum) {
        GroupOrderExample example=new GroupOrderExample();
        GroupOrderExample.Criteria criteria = example.createCriteria();
        criteria.andOrderNumEqualTo(orderNum);
        List<GroupOrder> groupOrders = groupOrderMapper.selectByExample(example);
        if (groupOrders!=null&&groupOrders.size()>0){
            GroupOrder groupOrder = groupOrders.get(0);
            return ServerResponse.getDataSuccess(groupOrder);
        }
        return ServerResponse.getDataFailed("订单不存在");
    }


    @Override
    public ServerResponse payOrder(Long orderNum) {
        ServerResponse groupOrdersr = this.getByOrderNum(orderNum);
        //先判断订单是否存在
        if (groupOrdersr.getStatus()!=1){
            return groupOrdersr;
        }
        GroupOrder groupOrder =(GroupOrder)groupOrdersr.getData();
        System.out.println("订单状态为"+groupOrder.getStatus());
        //订单存在，且状态为1
        if (groupOrder.getStatus()==1){
            return ServerResponse.getDataFailed("订单已支付，不要重新支付");
        }else if (groupOrder.getStatus()==4){ //订单存在，且状态为4
            return ServerResponse.getDataFailed("订单已超时，不要重新支付");
        }else if (groupOrder.getStatus()==3){ //订单存在，且状态为3
            return ServerResponse.getDataFailed("该订单已经退款，不要重新支付");
        }
        //支付时间
        Date payTime=new Date();
        //订单存在，且状态为2，判断是否超时
        if (groupOrder.getStatus()==2){
            Date overTime=groupOrder.getOverTime();
            if(payTime.getTime()>overTime.getTime()){
                //订单超时，改变订单状态
                byte status=4;
                groupOrder.setStatus(status);
                ServerResponse modify = this.modify(groupOrder);
                modify.setData("订单超时，已关闭");
                System.out.println("订单超时，已关闭");
                System.out.println("订单状态为"+groupOrder.getStatus());
                //将锁定的订单取消，redis库存＋1
                String groupName="group:"+groupOrder.getGroupId();
                redisTemplate.opsForValue().increment(groupName);
                //数据库已售数量减一
                ServerResponse groupInfsr = groupListService.getById(groupOrder.getGroupId());
                GroupList groupInf =(GroupList)groupInfsr.getData();
                groupInf.setGroupCount(groupInf.getGroupCount()-1);
                groupListService.modify(groupInf);
                System.out.println("redis:"+groupName+":"+redisTemplate.opsForValue().get(groupName));
                System.out.println("数据库:"+groupName+":"+groupInf.getGroupCount());
                return modify;
            }
        }else {
            //查询支付情况，返回的数据做判断
            //支付成功改变订单状态为1 设置支付时间
            byte status=1;
            groupOrder.setStatus(status);
            groupOrder.setPayTime(payTime);
            ServerResponse modify = this.modify(groupOrder);
            System.out.println("支付成功");
            System.out.println("订单状态为"+groupOrder.getStatus()+"支付时间为"+payTime);
            return ServerResponse.getDataSuccess("支付成功");
        }
        //生成流水号
        //支付不成功不改变订单状态，返回支付失败
        return ServerResponse.getDataSuccess("支付成功");
    }

    @Override
    public ServerResponse cancelOrder(Long orderNum) {
        ServerResponse groupOrdersr = this.getByOrderNum(orderNum);
        //先判断订单是否存在
        if (groupOrdersr.getStatus()!=1){
            return groupOrdersr;
        }
        GroupOrder groupOrder =(GroupOrder)groupOrdersr.getData();
        System.out.println("需要取消的订单状态为"+groupOrder.getStatus());
        //订单存在，且状态为4
        if (groupOrder.getStatus()==4){
            return ServerResponse.getDataFailed("订单超时，已取消");
        }
        //订单存在，且状态为3
        if (groupOrder.getStatus()==3){
            return ServerResponse.getDataFailed("订单已退款，已取消");
        }
        //订单存在，且状态为1
        if (groupOrder.getStatus()==1){
            //支付宝退款
            //根据流水号查询退款情况，返回的数据做判断
            //退款不成功不改变订单状态
            //return ServerResponse.getDataFailed("支付宝不可抗拒原因失败，请重试");
            //退款成功改变订单状态为3
            byte status=3;
            groupOrder.setStatus(status);
            ServerResponse modify = this.modify(groupOrder);
            //将退款的订单取消，redis库存＋1
            String groupName="group:"+groupOrder.getGroupId();
            redisTemplate.opsForValue().increment(groupName);
            //数据库已售数量加一
            ServerResponse groupInfsr = groupListService.getById(groupOrder.getGroupId());
            GroupList groupInf =(GroupList)groupInfsr.getData();
            groupInf.setGroupCount(groupInf.getGroupCount()-1);
            groupListService.modify(groupInf);
            System.out.println("redis:"+groupName+":"+redisTemplate.opsForValue().get(groupName));
            System.out.println("数据库:"+groupName+":"+groupInf.getGroupCount());
            return ServerResponse.getDataFailed("已退款，稍后返回到支付账号");
        }
        //订单存在，且状态为2
        if (groupOrder.getStatus()==2){
                //改变订单状态为4
                byte status=4;
                groupOrder.setStatus(status);
                ServerResponse modify = this.modify(groupOrder);
                modify.setData("订单已取消");
                System.out.println("订单已取消");
                System.out.println("订单状态为"+groupOrder.getStatus());
                //将锁定的订单取消，redis库存＋1
                String groupName="group:"+groupOrder.getGroupId();
                redisTemplate.opsForValue().increment(groupName);
                //数据库已售数量加一
                ServerResponse groupInfsr = groupListService.getById(groupOrder.getGroupId());
                GroupList groupInf =(GroupList)groupInfsr.getData();
                groupInf.setGroupCount(groupInf.getGroupCount()-1);
                groupListService.modify(groupInf);
                System.out.println("redis:"+groupName+":"+redisTemplate.opsForValue().get(groupName));
                System.out.println("数据库:"+groupName+":"+groupInf.getGroupCount());
                return modify;
            }
        return null;
    }

    @Override
    public ServerResponse scheduledCancel() {
        GroupOrderExample example=new GroupOrderExample();
        example.or(example.createCriteria().andStatusEqualTo(Byte.valueOf("2")));
        List<GroupOrder> groupOrders= groupOrderMapper.selectByExample(example);
        if (groupOrders!=null&&groupOrders.size()>0){
            List<Long> orderNums=new ArrayList();
            for (GroupOrder groupOrder:groupOrders){
                //支付时间
                Date nowTime=new Date();
                Date overTime=groupOrder.getOverTime();
                if(nowTime.getTime()>overTime.getTime()&&groupOrder.getOrderNum()!=null){
                    //订单超时，改变订单状态
                    byte status=4;
                    groupOrder.setStatus(status);
                    ServerResponse modify = this.modify(groupOrder);
                    //将锁定的订单取消，redis库存＋1
                    String groupName="group:"+groupOrder.getGroupId();
                    redisTemplate.opsForValue().increment(groupName);
                    //数据库已售数量加一
                    ServerResponse groupInfsr = groupListService.getById(groupOrder.getGroupId());
                    GroupList groupInf =(GroupList)groupInfsr.getData();
                    groupInf.setGroupCount(groupInf.getGroupCount()-1);
                    groupListService.modify(groupInf);
                    orderNums.add(groupOrder.getOrderNum());
                }
            }
            if(orderNums.size() != 0){
                System.out.println("有"+orderNums.size()+"订单已经超时,订单号如下");
                System.out.println(orderNums.toString());
                return ServerResponse.getDataSuccess("有"+orderNums.size()+"订单已经超时,订单号如下");
            }
        }

        return ServerResponse.getDataFailed("暂无超时订单");
    }

    @Override
    public GroupOrder getOrderById(Long orderNum) {
        GroupOrder groupOrder = (GroupOrder)this.getByOrderNum(Long.valueOf(orderNum)).getData();
        return groupOrder;
    }

    @Override
    public void updateOrderStatus(String orderNum, String alpayFlowNum, String paidAmount) {
        GroupOrder order = (GroupOrder)this.getByOrderNum(Long.valueOf(orderNum)).getData();

        //先修改订单状态
        byte status=1;
        order.setStatus(status);
        //修改支付时间
        order.setPayTime(new Date());
        groupOrderMapper.updateByPrimaryKeySelective(order);
        String flowId = sid.nextShort();
        Flow flow = new Flow();
        flow.setId(flowId);
        flow.setFlowNum(alpayFlowNum);
        flow.setBuyCounts(order.getProdCount());
        flow.setCreateTime(new Date());
        flow.setOrderNum(orderNum);
        flow.setPaidAmount(paidAmount);
        flow.setPaidMethod(1);
        flow.setProductId(order.getGroupId().toString());
        //添加流水
        flowMapper.insertSelective(flow);
    }

    @Override
    public ServerResponse payOrder(GroupOrder groupOrder) {
        return null;
    }

    public ServerResponse getByUserId(Integer userId) {
        GroupOrderExample example=new GroupOrderExample();
        GroupOrderExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId).andStatusGreaterThan(Byte.valueOf("0"));
        List<GroupOrder> groupOrderList = groupOrderMapper.selectByExample(example);
        if (groupOrderList != null)
        return ServerResponse.getDataSuccess(groupOrderList);
        return ServerResponse.getDataFailed("没有相关用户的订单");
    }

}
